<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 运费模板
 *
 * @icon fa fa-circle-o
 */
class Shippingtemplate extends Backend
{
	
	protected $relationSearch = true;
	/**
	 * ShippingTemplate模型对象
	 */
	protected $model = null;
	
	public function _initialize()
	{
		parent::_initialize();
		$this->model = model('ShippingTemplate');
		$this->view->assign("typeList", $this->model->getTypeList());
		$this->view->assign("isFreeList", $this->model->getIsFreeList());
		$this->view->assign("conditionFreeList", $this->model->getConditionFreeList());
		$this->view->assign("isAreaList", $this->model->getIsAreaList());
	}
	
	/**
	 * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
	 * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
	 * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
	 */
	
	
	/**
	 * 查看
	 */
	public function index()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isAjax()) {
			//如果发送的来源是Selectpage，则转发到Selectpage
			if ($this->request->request('keyField')) {
				return $this->selectpage();
			}
			list($where, $sort, $order, $offset, $limit) = $this->buildparams();
			
			
			$total = $this->model
				->with(['bus'])
				->where($where)
				->order($sort, $order)
				->count();
			
			$list = $this->model
				->with(['bus'])
				->where($where)
				->order($sort, $order)
				->limit($offset, $limit)
				->select();
			
			$list = collection($list)->toArray();
			$result = array("total" => $total, "rows" => $list);
			
			return json($result);
		}
		return $this->view->fetch();
	}
	
	
	/**
	 * 添加
	 */
	public function add()
	{
		if ($this->request->isPost()) {
			$params = $this->request->post("row/a");
			$items = $this->request->post("items/a");
			$conditions = $this->request->post('conditions/a');
			if ($params) {
				if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
					$params[$this->dataLimitField] = $this->auth->id;
				}
				
				Db::startTrans();
				try {
					//是否采用模型验证
					if ($this->modelValidate) {
						$name = basename(str_replace('\\', '/', get_class($this->model)));
						$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
						$this->model->validate($validate);
					}
					
					//查找名称是否已经存在,后台商家ID为1
					$row = Db::name('shippingTemplate')->where(['name' => $params['name'], 'business_id' => 1])->find();
					if($row){
						$this->error('模板名称已经存在');
					}
					//后台添加的为自营运费模板
					$params['business_id'] = 1;
					$result = $this->model->allowField(true)->save($params);
					if (!$result) {
						throw new Exception($this->model->getError());
					}
					
					$tempId = $this->model->getLastInsID();
					if($items){
						$itemRes = $this->model->addItems($tempId, $items, 1);
						if(!$itemRes){
							throw new Exception($this->model->getError());
						}
					}
					
					
					if($conditions){
						$conRes = $this->model->addConditions($tempId, $conditions, 1);
						if(!$conRes){
							throw new Exception($this->model->getError());
						}
					}
					
					
					
					Db::commit();
					$this->success();
				} catch (Exception $e) {
					Db::rollback();
					$this->error($e->getMessage());
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		
		$provinces = Db::name('area')->where(['parentid' => 0])->field('id,areaname')->select();
		return $this->view->fetch('edit', [
			'row' => [],
			'provinces' => json_encode($provinces),
			'items' => json_encode([['id' => '','area_ids' =>[], 'area_names' => [],'first' => 0,'amount' => '0','add' => 0,'add_amount' => 0]]),
			'conditions' => json_encode([['id' => '', 'area_ids' =>[], 'area_names' => [], 'amount' => 0, 'logic' => 1, 'weight' =>0]])
		]);
	}
	
	/**
	 * 编辑
	 */
	public function edit($ids = null)
	{
		$row = $this->model->get($ids);
		if (!$row) {
			$this->error(__('No Results were found'));
		}
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds)) {
			if (!in_array($row[$this->dataLimitField], $adminIds)) {
				$this->error(__('You have no permission'));
			}
		}
		if ($this->request->isPost()) {
			$params = $this->request->post("row/a");
			$items = $this->request->post("items/a");
			$conditions = $this->request->post('conditions/a');
			if ($params) {
				Db::startTrans();
				try {
					//是否采用模型验证
					if ($this->modelValidate) {
						$name = basename(str_replace('\\', '/', get_class($this->model)));
						$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
						$row->validate($validate);
					}
					
					$result = $row->allowField(true)->save($params);
					if ($result === false) {
						throw new Exception('更改出错：'.$row->getError().$row->getLastSql());
					}
					
					$tempId = $ids;
					if($items){
						$itemRes = $this->model->addItems($tempId, $items, 2);
						if(!$itemRes){
							throw new Exception('计算方式出错：'.$this->model->getError());
						}
					}
					
					
					if($conditions){
						$conRes = $this->model->addConditions($tempId, $conditions, 2);
						if(!$conRes){
							throw new Exception('更改条件出错：'.$this->model->getError());
						}
					}
					
					Db::commit();
					$this->success();
				} catch (Exception $e) {
					Db::rollback();
					$this->error($e->getMessage());
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		$provinces = Db::name('area')->where(['parentid' => 0])->field('id,areaname')->select();
		
		$items = Db::name('shippingTemplateItem')->where(['template_id' => $ids])->select();
		if($items){
			foreach ($items as $key => $item){
				$items[$key]['area_ids'] = explode(',', $item['area_ids']);
				$items[$key]['area_names'] = explode(',', $item['area_names']);
			}
		} else {
			$items = [['id' => '','area_ids' =>[], 'area_names' => [],'first' => 0,'amount' => '0','add' => 0,'add_amount' => 0]];
		}
		$conditions = Db::name(('shippingCondition'))->where(['template_id' => $ids])->select();
		if($conditions){
			foreach ($conditions as $key => $item){
				$conditions[$key]['area_ids'] = explode(',', $item['area_ids']);
				$conditions[$key]['area_names'] = explode(',', $item['area_names']);
			}
		} else {
			$conditions = [['id' => '', 'area_ids' =>[], 'area_names' => [],'amount' => 0, 'logic' => 1, 'weight' =>0]];
		}
		return $this->view->fetch('edit', [
			'row' => $row,
			'provinces' => json_encode($provinces),
			'items' => json_encode($items),
			'conditions' => json_encode($conditions),
		]);
	}
	
}
